package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

//操作验证码
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    //修改用户密码时发送验证码
    @RequestMapping("/send4ChangePassword")
    public Result send4ChangePassword(String telephone){
        //随机生成四位数验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        System.out.println("修改密码的验证码："+validateCode);
        //给用户发送验证码
        try {
            //使用工具类发送验证码，注释后可绕过短信发送
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            //发送验证码成功，并且将验证码保存到redis中（5分钟）
            Jedis resource = jedisPool.getResource();
            resource.setex(telephone+RedisMessageConstant.SENDTYPE_LOGIN,300,validateCode.toString());
            //一定要关闭jedisPool.getResource()需要手动返还到jedisPool中，不然会一直等待，也不会超时！！！！
            resource.close();
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //发送验证码失败
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    //手机身份验证
    @RequestMapping("/checkIdByTel")
    public Result checkIdByTel(HttpServletResponse response, @RequestBody Map map){
        //验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中获取保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //判断验证码是否输入正确
        if (validateCode!=null && validateCodeInRedis!=null && validateCode.equals(validateCodeInRedis)){
            //验证码输入正确
            //返还结果
            return new Result(true,"验证码输入正确");
        }else {
            //验证码输入错误
            return new Result(false,"验证码输入错误");
        }
    }

}
